package com.robot.core;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import com.robot.util.TextUtils;

public class Config {
	private Map<String,String> configMap = new HashMap<String,String>();
	private Map<Long,Long> timeMap = new HashMap<Long,Long>();
	
	public Config() {
		init();
	}
	private void init() {
		String userPath = System.getProperty("user.dir");
		File dir = new File(new File(userPath),"source/config");
		if(!dir.exists()){
			dir.mkdirs();
		}
		File file = new File(dir,"机器人配置.ini");
		if(!file.exists()){
			initConfigFile(file);
		}
		loadConfig(dir);
	}

	private void initConfigFile(File file) {
		configMap.put("robotname", "小风车");
		configMap.put("password", " ");
		configMap.put("qq", "361956936");
		writeFile(file);
	}

	private void writeFile(File file) {
		StringBuffer outPutString = new StringBuffer();
		for(Entry<String, String> entry:configMap.entrySet()){
			outPutString.append(entry.getKey()+"="+entry.getValue()+"\n");
		}
		TextUtils.writeText(outPutString.toString(), file.getAbsolutePath(),"GBK");
	}

	private void loadConfig(File dir) {
		for (File file : dir.listFiles()) {
			List<String> lines = TextUtils.readLine(file.getAbsolutePath(),"GBK");
			for (String line : lines) {
				if (Pattern.matches("^(?!#).+=.+$", line)) {
					String[] data = line.split("=");
					configMap.put(data[0].trim(), data[1].trim());
				}
			}
		}
	}
	public String get(String key){
		return this.configMap.get(key);
	}
	public void put(String key,String value){
		this.configMap.put(key, value);
	}
	public Long get(Long key){
		return this.timeMap.get(key);
	}
	public void put(Long key,Long value){
		this.timeMap.put(key, value);
	}
	public Map<String, String> getConfigMap() {
		return configMap;
	}
	public void setConfigMap(Map<String, String> configMap) {
		this.configMap = configMap;
	}
	
}
